package cn.hxth.cloud.api.rabbitmq;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;

public abstract class AbstractRabbitMQHandler {
   private Logger logger ;
   private  RabbitMQSender rabbitMQSender ;

    public AbstractRabbitMQHandler(RabbitMQSender rabbitMQSender) {
        this.rabbitMQSender = rabbitMQSender;
       ;
    }

    protected void setLogger(Class<?> clazz) {
        this.logger = LoggerFactory.getLogger(clazz) ;
    }

    @RabbitHandler
    public void process(String message) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        JSONObject jsonObject = JSONObject.parseObject(message); // 字符串转json
        String messageId = jsonObject.getString("messageId"); // 取得此条信息
        String data = jsonObject.getString("data");
        try {
            String methodName = "process" + jsonObject.getString("eventType").substring(0, 1).toUpperCase() + jsonObject.getString("eventType").substring(1);
            Method method = this.getClass().getDeclaredMethod(methodName, JSONObject.class, String.class);
            method.setAccessible(true);
            Boolean flag = (Boolean) method.invoke(this, jsonObject, data);
           /* this.redisTemplate.opsForValue().set(messageId, String.valueOf(flag));*/
            System.out.println(flag);
        } catch (Exception e) {
            logger.error("error", e);
          /*  this.redisTemplate.opsForValue().set(messageId, String.valueOf(false));*/
        }

    }
    protected synchronized   void sendMessage(String name,Object data,String eventType,String mid)throws Exception{
        Long wait = 0l ;
        JSONObject jsonObject  = new JSONObject() ;

        Boolean flag = null ;
        String messageId = UUID.randomUUID().toString() ;
        jsonObject.put("eventType",eventType) ;
        jsonObject.put("data",data) ;
        jsonObject.put("messageId",messageId) ;
        if(mid!=null){
            jsonObject.put("mid",mid) ;
        }
        this.rabbitMQSender.send(RabbitQueue.DATA_CHANGE_QUEUE+"-"+name,jsonObject.toJSONString());
       /* while (true){

            if(this.redisTemplate.opsForValue().get(messageId) == null){
                System.out.println(this.redisTemplate.opsForValue().get(messageId)+"------------------------------------"+messageId);
                Thread.sleep(20);
                wait = wait+20 ;
                continue;
            }
            else{
                flag = Boolean.valueOf(this.redisTemplate.opsForValue().get(messageId)) ;
                break;
            }
        }*/
       /* this.redisTemplate.delete(messageId);*/
        /*if(!flag){
            {
                throw new RuntimeException("相关微服务处理失败") ;
            }

        }*/

    }
}
